<template>
  <div>
    <div class="box-card">
      <div class="box-header">
        <div class="header-top">
          <div class="header-left">
            <el-input
              v-model="input"
              placeholder="根据用户名搜索"
              style="width: 200px; margin-right: 15px"
            ></el-input>
            <el-row>
              <el-button class="header-btn" @click="clearInput">清空</el-button>
              <el-button type="primary" class="header-btn" @click="searchInput"
                >搜索</el-button
              >
            </el-row>
          </div>
          <el-button
            type="success"
            class="header-right"
            @click="openDialog('add')"
            ><i class="el-icon-edit"></i> 新增用户</el-button
          >
        </div>
        <div class="header-content">
          <i class="el-icon-info"></i>
          <span>共{{ total }}条记录</span>
        </div>
      </div>
      <el-table
        label-width="150px"
        :data="tableData"
        style="width: 100%"
        max-height="660"
        v-loading="loading"
        element-loading-text="给我一点时间"
        :header-cell-style="{ background: '#f4f4f5' }"
      >
        <el-table-column prop="id" label="序号" align="center">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center">
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" align="center">
        </el-table-column>
        <el-table-column prop="username" label="用户名" align="center">
        </el-table-column>
        <el-table-column
          prop="permission_group_title"
          label="权限组名称"
          width="160"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="role" label="角色" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button
              v-show="row.id != 2"
              type="primary"
              icon="el-icon-edit"
              circle
              class="edit1"
              @click="openDialog('edit', row.id)"
            ></el-button>
            <el-button
              v-show="row.id != 2"
              type="danger"
              icon="el-icon-delete"
              circle
              class="edit2"
              @click="open(row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagesize"
        :total="total"
        layout="prev,pager, next,sizes, jumper"
      >
      </el-pagination>
    </div>
    <!-- 弹出框 -->
    <el-dialog
      :title="diologTitle"
      :visible.sync="dialogFormVisible"
      width="645"
      @close="closeDialog"
    >
      <el-form :model="form" :rules="rules" label-width="90px" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="titleType === 'add'">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="form.role"></el-input>
        </el-form-item>
        <el-form-item label="权限组名称">
          <el-select v-model="form.grouptitle" placeholder="请选择">
            <el-option
              v-for="item in limitlists"
              :key="item.id"
              :label="item.permission_group_title"
              :value="item.title"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="form.tel"></el-input>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input
            type="textarea"
            v-model="form.desc"
            placeholder="Please input"
          ></el-input>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="addOrUpdataData(id)"
            >确 定</el-button
          >
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { list, remove, add, detail, update } from '@/api/base/users.js'
import { list as limitlist } from '@/api/base/permissions.js'
export default {
  data () {
    return {
      input: '',
      tableData: [],
      page: 1,
      pagesize: 10,
      total: 0,
      loading: false,
      form: {
        username: '',
        email: '',
        password: '',
        role: '',
        grouptitle: '',
        tel: '',
        desc: ''
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      limitlists: '',
      titleType: 'add',
      id: ''
    }
  },

  async created () {
    this.initTable()
    const { data } = await limitlist({
      page: this.page,
      pagesize: this.pagesize,
      keyword: this.input
    })
    console.log(data)
    this.limitlists = data.list
  },

  methods: {
    // 清空表单内容
    clearForm () {
      this.form = {
        username: '',
        email: '',
        password: '',
        role: '',
        grouptitle: '',
        tel: '',
        desc: ''
      }
    },
    async initTable () {
      const { data } = await list({
        page: this.page,
        pagesize: this.pagesize,
        keyword: this.input
      })
      console.log(data)
      this.tableData = data.list
      this.total = data.counts
    },
    // pagesize改变时
    handleSizeChange (val) {
      this.pagesize = val
      this.page = 1
      this.initTable()
    },
    // page改变时
    handleCurrentChange (val) {
      this.page = val
      this.initTable()
    },
    // 清空input
    clearInput () {
      this.input = ''
      this.loading = true
      this.initTable()
      this.loading = false
    },
    // 搜索input
    searchInput () {
      this.loading = true
      this.tableData = this.tableData.filter(
        item => item.username === this.input
      )
      this.loading = false
    },
    // 对话框取消按钮
    closeDialog () {
      this.clearForm()
      this.$refs.form.resetFields()
      this.dialogFormVisible = false
    },

    // 点击新增用户按钮
    async openDialog (type, id) {
      this.titleType = type
      console.log(id)
      if (type !== 'add') {
        const { data } = await detail({ id })
        console.log(data)
        this.id = data.id
        const str = this.limitlists.find(
          item => item.id === data.permission_group_id
        )

        this.form.email = data.email
        this.form.username = data.username
        this.form.role = data.role
        this.form.grouptitle = str ? str.title : data.permission_group_id
        this.form.tel = data.phone
        this.form.desc = data.introduction
      }
      this.dialogFormVisible = true
    },
    // 删除 取消确认按钮
    open (id) {
      this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 发删除请求
          await remove({ id })
          this.initTable()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作！'
          })
        })
    },
    // 新增和修改
    async addOrUpdataData (id) {
      try {
        this.$refs.form.validate()
        if (this.titleType === 'add') {
          const id = this.limitlists.find(
            item => item.title === this.form.grouptitle
          ).id
          console.log(id)
          const data = await add({
            avatar: '',
            email: this.form.email,
            introduction: this.form.desc,
            password: this.form.password,
            permission_group_id: id,
            phone: this.form.tel,
            role: this.form.role,
            username: this.form.username
          })
          console.log(data)
        }
        if (this.titleType === 'edit') {
          const ids = this.limitlists.find(
            item => item.title === this.form.grouptitle
          ).id
          console.log(ids)
          await update({
            id,
            avatar: '',
            email: this.form.email,
            introduction: this.form.desc,
            permission_group_id: ids,
            phone: this.form.tel,
            role: this.form.role,
            username: this.form.username
          })
        }
        this.clearForm()
        this.$refs.form.resetFields()
        this.initTable()
        this.$message.success(
          this.titleType === 'add' ? '添加成功' : '修改成功'
        )
        this.dialogFormVisible = false
      } catch (error) {
        this.$message.error('请填入必填项')
      }
    }
  },
  computed: {
    diologTitle () {
      if (this.titleType === 'add') {
        return '创建用户'
      } else if (this.titleType === 'edit') {
        return '编辑用户'
      } else {
        return '创建用户'
      }
    }
  }
}
</script>

<style scoped lang="less">
.box-card {
  margin: 20px;
  background-color: #fff;
  padding: 20px;
  .box-header {
    .header-top {
      height: 45px;
      margin-bottom: 10px;
      .header-left {
        display: flex;
        .header-btn {
          width: 60px;
          font-size: 12px;
        }
      }
      .header-right {
        width: 90px;
        height: 32px;
        font-size: 12px;
        float: right;
        margin-top: -36px;
        .el-icon-edit {
          margin-left: -6px;
        }
      }
    }
    .header-content {
      background-color: #f4f4f5;
      color: #909399;
      font-size: 13px;
      padding-left: 8px;
      height: 40px;
      line-height: 40px;
      margin-bottom: 20px;
      .el-icon-info {
        margin-right: 5px;
      }
    }
  }
  .edit1 {
    color: #409eff;
    background: #ecf5ff;
    border-color: #b3d8ff;
    &:hover {
      background-color: #409eff;
      color: #fff;
    }
  }
  .edit2 {
    color: #f56c6c;
    background: #fef0f0;
    border-color: #fbc4c4;
    &:hover {
      background-color: #f56c6c;
      color: #fff;
    }
  }
  .el-pagination {
    height: 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20px;
  }
}

.el-dialog {
  .el-form {
    width: 400px;
    margin: auto;
    .el-input {
      width: 310px;
      height: 35px;
    }
  }
  .dialog-footer {
    margin-top: 60px;
    text-align: center;
  }
}
</style>
